import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext


# 得到一个sqlite数据库链接
def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row
    return g.db


# 得到数据类型为字典的sqlite语句
def get_db_dict():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = make_dicts
    return g.db


# 将游标转换为字典
def make_dicts(cursor, row):
    return dict((cursor.description[idx][0], value)
                for idx, value in enumerate(row))


# 关闭数据库连接
def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()


# 初始化数据库
def init_db():
    db = get_db()
    with current_app.open_resource('schema.sql') as f:
        db.executescript(f.read().decode('utf-8'))


@click.command('init-db')
@with_appcontext
def init_db_command():
    init_db()
    click.echo("初始化数据库")


def init_app(app):
    try:
        with app.app_context():
            print("这是app", app == current_app)
            app.teardown_appcontext(close_db)
            app.cli.add_command(init_db_command)
    except Exception as e:
        print("发生了异常", e)




